// 入口文件
const {
  addChatNewsControl,
  queryChatNewsControl,
  addChatGroupSocket,
} = require("./controller/chatController");
const {
  queryArticleByIdService,
  modifyServiceSocket,
} = require("./service/article.service");
const { queryGroupByIdService } = require("./service/chat.service");
const app = require("./app/index");
const { APP_PORT } = require("./config/default.js");
const http = require("http");
const io = require("socket.io");
const maxmind = require("maxmind"); //查找ip属地信息
const server = http.createServer(app.callback());
// socket.io设置跨域
const socketServer = io(server, {
  cors: {
    origin: "*",
  },
});
app.use((ctx, next) => {
  ctx.body = "hello api222";
});

socketServer.on("connection", (socket) => {
  //   // 获取客户端的IP地址
  //   const clientIP = socket.request.connection.remoteAddress;
  //   console.log("Client IP:", clientIP);

  //   // 通过IP地址查询地理位置
  //   maxmind.open("path/to/GeoLite2-City.mmdb", (err, cityLookup) => {
  //     if (err) {
  //       console.error(err);
  //     } else {
  //       const ipAddress = " 192.168.56.1"; // 要查询的IP地址
  //       const city = cityLookup.get(ipAddress);
  //       console.log(city);
  //     }
  //   });

  socket.emit("open"); //通知客户端已连接
  console.log("connected");
  //监听disconnect事件
  socket.on("disconnect", () => {
    console.log("disconnect");
  });

  // 接收到客户端传过来的数据
  socket.on("send", async (value) => {
    let data = JSON.parse(value);
    console.log(data, "send");
    const flag = await queryGroupByIdService(data.groupId);
    if (!flag) {
      let userId = data.groupId.split(",")[0];
      let requestObj = {
        id: data.groupId,
        userId,
      };
      const addStatus = await addChatGroupSocket(requestObj);
    }
    console.log(flag, "flag");
    const id = await addChatNewsControl(data);
    const res = await queryChatNewsControl({ id });
    console.log(res, "?????");

    // 这两种写法的区别是，前者会向除了当前socket连接之外的所有客户端发送消息，而不包括当前socket连接。而后者则包括自身socket连接。
    // socket.broadcast.emit("userin", JSON.stringify(res));
    socketServer.emit("update", JSON.stringify(res));
  });

  // 文章点赞
  socket.on("dianzan", async (value) => {
    console.log(value, "点赞");
    let requstObj = JSON.parse(value);
    let res = await queryArticleByIdService({ id: requstObj.articleId });
    let ids = res[0].dianzanIds;
    console.log(ids, "ids");
    console.log(requstObj.status, "flag");

    if (requstObj.status) {
      if (!ids) {
        let ids = requstObj.userId + "";
        await modifyServiceSocket({ id: requstObj.articleId, dianzanIds: ids });
      } else {
        let arr = ids.split(",");
        let flag = arr.find(item=>item===requstObj.userId+"");
        if(flag) {
          return;
        }
        arr.push(requstObj.userId + "");
        let idstr = arr.join(",");
        console.log(idstr, "idstr");
        await modifyServiceSocket({ id: requstObj.articleId, dianzanIds: idstr });
      }
    } else {
      let arr = ids.split(",");
      console.log(arr,"修改前的数组")
      arr = arr.filter((item) => item != requstObj.userId + "");
      console.log(arr,"修改后的数组")

      let idstr = arr.join(",") || "";
      console.log(idstr, "idstr---");
      await modifyServiceSocket({ id: requstObj.articleId, dianzanIds: "" });
     
    }
    socket.emit("response","dianzan");
  });

  // 收藏
  socket.on("collect", async (value) => {
    console.log(value, "收藏");
    let requstObj = JSON.parse(value);
    let res = await queryArticleByIdService({ id: requstObj.articleId });
    let ids = res[0].collectIds;
    console.log(ids, "ids");
    console.log(requstObj.status, "flag");

    if (requstObj.status) {
      if (!ids) {
        let ids = requstObj.userId + "";
        await modifyServiceSocket({ id: requstObj.articleId, collectIds: ids });
      } else {
        let arr = ids.split(",");
        let flag = arr.find(item=>item===requstObj.userId+"");
        if(flag) {
          return;
        }
        console.log(flag,"是否有相同")
        arr.push(requstObj.userId + "");
        let idstr = arr.join(",");
        console.log(idstr, "idstr+++");
        await modifyServiceSocket({ id: requstObj.articleId, collectIds: idstr });
      }
    } else {
      let arr = ids.split(",");
      console.log(arr,"修改前的数组收藏")
      arr = arr.filter((item) => item != requstObj.userId + "");
      console.log(arr,"修改后的数组收藏")

      let idstr = arr.join(",") || "";
      console.log(idstr, "idstr---");
      await modifyServiceSocket({ id: requstObj.articleId, collectIds: "" });
    }
    socket.emit("response","collect");

  });
});

server.listen(APP_PORT, () => {
  console.log(`server is running on http://localhost:${APP_PORT}`);
});

// app.listen(APP_PORT,()=>{
//     console.log(`server is running on http://localhost:${APP_PORT}`);
// })

module.exports = server;
